package com.lc.user.express.ordering;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.overlay.DrivingRouteOverlay;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.RouteSearch.OnRouteSearchListener;
import com.amap.api.services.route.WalkRouteResult;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lc.user.express.BaseSecondActivity;
import com.lc.user.express.MainActivity;
import com.lc.user.express.R;
import com.lc.user.express.app.AppContext;
import com.lc.user.express.httpserver.GetOrderCancel;
import com.lc.user.express.httpserver.GetOrderChoosed;
import com.lc.user.express.ordermanagement.OrderDetailsActivity;
import com.lc.user.express.utils.GetToast;
import com.lc.user.express.utils.PublicMethod;
import com.lc.user.express.view.StarViewNotClick;
import com.lc.user.express.view.dialog.AffirmDialog;
import com.zcx.helper.http.AsyCallBack;


/**
 * Created by Administrator on 2016/4/12.司机已接单
 */
public class OrderReceivedActivity extends BaseSecondActivity implements AMap.OnMarkerClickListener, OnRouteSearchListener, AMap.OnInfoWindowClickListener, AMap.InfoWindowAdapter {
    private SimpleDraweeView riv_head;//头像
    private TextView tv_diver_name, tv_diver_disc;//姓名 服务次数 车牌号
    private MapView mapView;
    private AMap aMap;
    private RouteSearch mRouteSearch;
    private DriveRouteResult mDriveRouteResult;
    private LatLng slatLng;//发货地址经纬度
    private LatLng dlatLng;//司机位置经纬度
    private Marker marker;
    private ImageView iv_call;//打电话
    private String mobile = "";//电话号码
    private StarViewNotClick starView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_received);
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState); // 此方法必须重写
        setTitle("派单中");
        init();
        initView();
        orderChoosed();

    }

    private void initView() {
        starView = (StarViewNotClick)findViewById(R.id.sv);
        riv_head = (SimpleDraweeView) findViewById(R.id.riv_head);
        tv_diver_name = (TextView) findViewById(R.id.tv_driver_name);
        tv_diver_disc = (TextView) findViewById(R.id.tv_driver_disc);
        iv_call = (ImageView) findViewById(R.id.iv_call);
        iv_call.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.head_right:
                new AffirmDialog(cnt, "您确定要取消该订单吗？", "取消", "确定", R.style.MyDialog) {

                    @Override
                    protected void onYesClick() {
                        // TODO Auto-generated method stub
                        cancelOrder();
                    }
                }.show();
                break;
            case R.id.iv_call:
                if (!TextUtils.isEmpty(mobile)) {
                    PublicMethod.callPhone(cnt, mobile);
                } else {
                    GetToast.useString(cnt, "暂无电话号码");
                }
                break;
        }
    }

    private void orderChoosed() {
        new GetOrderChoosed(getIntent().getStringExtra("orderid"), AppContext.myPreferences.getUid(), new AsyCallBack<GetOrderChoosed.Info>() {
            @Override
            public void onSuccess(String toast, int type, GetOrderChoosed.Info info) throws Exception {
                super.onSuccess(toast, type, info);
                tv_diver_name.setText(info.name);
                starView.setSelect((int)Math.round(info.star)-1);
                tv_diver_disc.setText("近期服务" + info.number + "次 " + info.city + " " + info.license);
               // ImageManager.from(cnt).displayImage(riv_head, info.avatar, R.mipmap.default_pic);

                riv_head.setImageURI(Uri.parse(info.avatar));
                mobile = info.mobile;
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);

            }
        }).execute(cnt);//调接口
    }

    private void cancelOrder() {
        new GetOrderCancel(AppContext.myPreferences.getUid(), getIntent().getStringExtra("orderid"), new AsyCallBack<Object>() {
            @Override
            public void onSuccess(String toast, int type, Object info) throws Exception {
                super.onSuccess(toast, type, info);
                show(MainActivity.class);
                sendBroadcast(new Intent(MainActivity.SWICH_FRAGMENT));
                finish();
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                if (!TextUtils.isEmpty(toast)) GetToast.useString(cnt, toast);
            }
        }).execute(cnt);//调接口
    }

    /**
     * 初始化AMap对象
     */
    private void init() {

        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
    }

    private void setUpMap() {
        aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
        aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
        String s = getIntent().getStringExtra("spoint");
        String d = getIntent().getStringExtra("dpoint");
        String[] ss = s.split(",");
        String[] dd = d.split(",");
        slatLng = new LatLng(PublicMethod.strToDouble(ss[0]), PublicMethod.strToDouble(ss[1]));
        dlatLng = new LatLng(PublicMethod.strToDouble(dd[0]), PublicMethod.strToDouble(dd[1]));
        marker = aMap.addMarker(new MarkerOptions()
                .position(dlatLng)
                .icon(BitmapDescriptorFactory.fromBitmap(
                        BitmapFactory.decodeResource(getResources(), R.mipmap.cars))));
        marker.setTitle("司机");
        aMap.addMarker(new MarkerOptions()
                .position(slatLng)
                .icon(BitmapDescriptorFactory.fromBitmap(
                        BitmapFactory.decodeResource(getResources(), R.mipmap.addr_start))));
        aMap.moveCamera(CameraUpdateFactory.zoomTo(11));
        aMap.getUiSettings().setZoomControlsEnabled(false);//隐藏放大缩小按钮
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示


//        mRouteSearch = new RouteSearch(this);
//        mRouteSearch.setRouteSearchListener(this);
        marker.showInfoWindow();
        zoomToSpan();
//        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
//                PublicMethod.convertToLatLonPoint(slatLng), PublicMethod.convertToLatLonPoint(elatLng));
//        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, RouteSearch.DrivingDefault, null,
//                null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
//        mRouteSearch.calculateDriveRouteAsyn(query);
    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int errorCode) {
        if (errorCode == 1000) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    mDriveRouteResult = result;
                    final DrivePath drivePath = mDriveRouteResult.getPaths()
                            .get(0);
                    DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
                            this, aMap, drivePath,
                            mDriveRouteResult.getStartPos(),
                            mDriveRouteResult.getTargetPos());
                    drivingRouteOverlay.removeFromMap();
                    drivingRouteOverlay.addToMap();

                    drivingRouteOverlay.setThroughPointIconVisibility(false);
                    zoomToSpan();


                } else if (result != null && result.getPaths() == null) {

                }

            } else {

            }
        } else {

        }
    }

    public void zoomToSpan() {
        if (aMap == null)
            return;
//        LatLngBounds bounds = getLatLngBounds();
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(dlatLng));

    }

//    private LatLngBounds getLatLngBounds() {
//        LatLngBounds.Builder b = LatLngBounds.builder();
//        b.include(slatLng);
//        b.include(elatLng);
//        return b.build();
//    }

    @Override
    public View getInfoContents(Marker marker) {

        return null;
    }

    /**
     * 监听自定义infowindow窗口的infowindow事件回调
     */
    @Override
    public View getInfoWindow(Marker marker) {
        View infoWindow = getLayoutInflater().inflate(
                R.layout.map_window_view, null);
        AppContext.ScaleScreenHelper.loadView((ViewGroup) infoWindow);
        LinearLayout ll_order = (LinearLayout) infoWindow.findViewById(R.id.ll_order);
        ll_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("orderid", getIntent().getStringExtra("orderid"));
                show(OrderDetailsActivity.class, OrderDetailsActivity.TYPE_1, bundle);
            }
        });
        return infoWindow;
    }

    @Override
    public void onInfoWindowClick(Marker marker) {
//        ToastUtil.show(this, "你点击了infoWindow窗口" + marker.getTitle());
    }

    @Override
    public boolean onMarkerClick(final Marker marker) {

        return false;
    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult result, int errorCode) {

    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }

    @Override
    public void onBusRouteSearched(BusRouteResult result, int errorCode) {

    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onBackPressed() {
        show(MainActivity.class);
        sendBroadcast(new Intent(MainActivity.SWICH_FRAGMENT));
        finish();
    }
}
